package club.worldbang.structures.stack;

import java.io.Serializable;
import club.worldbang.structures.linkedList.singleLinked.Node;

//栈的链表实现
public class LinkedStack<T> implements Serializable, Stack<T> {

	private static final long serialVersionUID = 5493359215581913648L;
	private Node<T> top;
	private int size;

	public LinkedStack() {
		this.top = new Node<>();
	}

	public int size() {
		return size;
	}

	@Override
	public boolean isEmpty() {
		return top == null || top.data == null;
	}

	@Override
	public void push(T data) {
		if (data == null) {
			throw new RuntimeException("data can`t null");
		}
		if (this.top == null) {
			this.top = new Node<>(data);
		} else if (this.top.data == null) {
			this.top.data = data;
		} else {
			Node<T> p = new Node<>(data, this.top);
			top = p;// 更新栈顶
		}
		size++;
	}

	@Override
	public T peek() {
		// 栈是否可读
		if (isEmpty()) {
			throw new RuntimeException("stack is empty");
		}
		return top.data;
	}

	@Override
	public T pop() {
		if (isEmpty()) {
			throw new RuntimeException("stack is empty");
		}
		T data = this.top.data;
		top = top.next;
		size--;
		return data;
	}

}
